package sso

import (
	"encoding/json"
	"errors"
	"log"
	"youdu/config"
	modelYoudu "youdu/model/youdu"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/go-resty/resty/v2"
)

var SessionKey = "Identify"

func SetIdentifyFromDemo(c *gin.Context) {
	id := modelYoudu.Identify{
		Buin: 16109396,
		UserInfo: modelYoudu.UserInfo{
			Gid:     100023,
			Account: "zhangsan",
			ChsName: "张三",
		},
		Status: modelYoudu.Status{
			Code:    0,
			Message: "登录成功",
		},
	}
	SetIdentifyToSession(c, id)
}
func SetIdentifyToContext(c *gin.Context, Identify modelYoudu.Identify) {
	// 设置到上下文
	c.Set(SessionKey, Identify)
}
func SetIdentifyToSession(c *gin.Context, Identify modelYoudu.Identify) {
	var userJsonByte []byte
	session := sessions.Default(c)
	// 将结构体对象序列化为 JSON 字符串更新到 session
	userJsonByte, _ = json.Marshal(Identify)
	session.Set(SessionKey, string(userJsonByte))
	session.Save()
	// log.Println("SetIdentifyToSession:", Identify)
	SetIdentifyToContext(c, Identify)
}
func GetIdentifyFromSession(c *gin.Context) (modelYoudu.Identify, error) {
	var Identify modelYoudu.Identify
	session := sessions.Default(c)
	// 从cookie中获取
	v := session.Get(SessionKey)
	if v == nil {
		return Identify, errors.New("session is empty")
	} else {
		// 将 JSON 字符串反序列化为结构体对象
		err := json.Unmarshal([]byte(v.(string)), &Identify)
		if err != nil {
			return Identify, errors.New("json decode error " + err.Error())
		}
	}
	return Identify, nil
}
func CurrentUserName(c *gin.Context) string {
	user := CurrentUser(c)
	username := user.ChsName + "(" + user.Account + ")"
	return username
}
func CurrentUser(c *gin.Context) modelYoudu.UserInfo {
	return CurrentIdentify(c).UserInfo
}
func CurrentIdentify(c *gin.Context) modelYoudu.Identify {
	return c.MustGet(SessionKey).(modelYoudu.Identify)
}
func LoginByToken(token string) (modelYoudu.Identify, error) {
	client := resty.New()

	// url := "http://127.0.0.1:7080/cgi/identify?token=" + token
	url := config.Inst.Entprise.ApiServer + "/cgi/identify?token=" + token
	var id modelYoudu.Identify

	resp, err := client.R().
		SetResult(&modelYoudu.Identify{}). // 自动解析 JSON 到结构体
		Execute("GET", url)

	if err != nil {
		log.Println("Error:", err)
		return id, err
	}
	// 安全的类型断言
	if response, ok := resp.Result().(*modelYoudu.Identify); ok {
		// 断言成功
		id = *response
		// log.Println("Response:", id.Status.Code, id.Status.Message)
		if id.Status.Code == 0 {
			return id, nil
		} else {
			return id, errors.New("SSO登录失败：" + id.Status.Message)
		}
	} else {
		// 断言失败
		log.Println("LoginByToken断言失败")
		return id, errors.New("断言失败")
	}
}
